//generate tab and mark complete?
package edu.towson.cosc716.Commands;

import java.util.LinkedList;
import java.util.List;

import edu.towson.cosc716.interfaces.Command;
import edu.towson.cosc716.interfaces.Component;
import edu.towson.cosc716.iterators.GetTabByTable;
import edu.towson.cosc716.models.InformationAggregator;
import edu.towson.cosc716.models.MenuItem;
import edu.towson.cosc716.models.Offer;
import edu.towson.cosc716.models.Order;
import edu.towson.cosc716.models.Tab;
import edu.towson.cosc716.models.TabItem;

// TODO: Auto-generated Javadoc
/**
 * The Class PayBillCmd.
 */
public class PayBillCmd implements Command
{
	
	/** The table id. */
	private int tableId;
	
	/** The information aggregator. */
	private InformationAggregator informationAggregator;
	
	
	/**
	 * Instantiates a new pay bill cmd.
	 *
	 * @param tableId the table id
	 * @param informationAggregator the information aggregator
	 */
	public PayBillCmd (int tableId, InformationAggregator informationAggregator)
	{
		this.tableId = tableId;
		this.informationAggregator = informationAggregator;
		
	}

	/* (non-Javadoc)
	 * @see edu.towson.cosc716.interfaces.Command#execute()
	 */
	@Override
	public Object execute() throws Exception 
	{
		List<Order> myOrders = informationAggregator.preparedOrders.getOrdersForTable(tableId);
		Tab myTab = new Tab(tableId);
		TabItem myTabItem;
		MenuItem myMenuItem;
		Component componant = null;
		
		for (int x = 0; x< myOrders.size(); x++)
		{
			myMenuItem = informationAggregator.menu.find(myOrders.get(x).getMenuItemId());
			myTabItem = new TabItem(myMenuItem.getDescription(), myMenuItem.getCurrentPrice());
			myTab.addTabItem(myTabItem);
			informationAggregator.preparedOrders.remove(myOrders.get(x));
			informationAggregator.paidOrders.add(myOrders.get(x));
		}
		float total = myTab.calculate();
		boolean hasOffer = false;
		for (int i = 0; i < informationAggregator.offers.size(); i++) {
			Offer offer = informationAggregator.offers.get(i);
			if (total > offer.getOfferMinPrice()) {
				offer.setTab(myTab);
				hasOffer = true;
				componant = offer;
				// Used for testing.
				//System.out.println("Offer Applied: Total Prediscount = " + myTab.calculate() + " Total after discount = " + componant.calculate());
				break;
			}
		}
		
		if (!hasOffer) {
			componant = myTab;
		}
		return componant;
	}

}
